<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends SMB_Controller {
	
	public function __construct() {
		parent::__construct();
		$this->load->library('data');
		$this->load->library('scholarship');
	}
	
	public function index() {
		$this->_get_userinfo();
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'profile'));
		$params = array(
			'student' => $this->data->get_student($this->userinfo['username']),
			'scholarships' => $this->scholarship->get_scholarship_history($this->userinfo['username']),
			'registrations' => $this->scholarship->get_register_history($this->userinfo['username'])
		);
		$this->load->view('mahasiswa/profile', $params);
		$this->_load_common_footer();
	}
	
	public function userphoto() {
		$this->_get_userinfo();
		$this->load->helper('download');
		$filename = do_hash($this->userinfo['username'].'.jpg', 'sha1');
		$pathfile = 'files/userphoto/'.$filename;
		if (file_exists($pathfile)) {
			$name = $this->userinfo['username'].'.jpg';
		} else {
			$pathfile = 'files/userphoto/'.do_hash('default.jpg', 'sha1');
			$name = 'default.jpg';
		}
		$data = file_get_contents($pathfile);
		force_download($name, $data);
	}
	
	public function changephoto() {
		$this->_get_userinfo();
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'profile'));
		
		$status = $this->input->post('upload');
		if ($status == FALSE) {
			$params = array(
				'result' => ''
			);
		} else {
			$config['upload_path'] = 'files/userphoto/';
			$config['allowed_types'] = 'jpg';
			$config['max_size'] = MAX_PHOTO_SIZE;
			$config['max_width'] = '400';
			$config['max_height'] = '400';
			$config['same_dimensions'] = TRUE;
			$config['overwrite'] = TRUE; 
			$config['file_name'] = do_hash($this->userinfo['username'].'.jpg', 'sha1');
			$this->load->library('upload', $config);
			
			if (!$this->upload->do_upload('photo')) {
				$params = array(
					'result' => $this->upload->display_errors('<br /><span class="error">', '</span>')
				);
			} else {
				$filename = 'files/userphoto/'.do_hash($this->userinfo['username'].'.jpg', 'sha1'); 
				$result = rename($filename.'.jpg', $filename);
				if ($result == FALSE) {
					unlink($filename.'.jpg');
					$params = array(
						'result' => '<br /><span class="error">Foto gagal diganti. Silakan coba beberapa saat lagi.</span>'
					);
				} else {
					$params = array(
						'result' => '<br /><span class="info">Foto berhasil diganti.</span>'
					);
				}
			}
		}
		
		$this->load->view('mahasiswa/upload_photo', $params);
		$this->_load_common_footer();
	}
}